package com.getpebble.android.jskit.webapps;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.jskit.concurrency.SyncStepRunnable;
import com.getpebble.android.jskit.webapps.WebappSupport.QueuedLoadUrlContainer;
import com.getpebble.android.jskit.webapps.WebappSupport.QueuedLoadUrlContainer.LoadTypeE;
import com.getpebble.android.jskit.webapps.WebappSupport.WebViewControlled;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.json.JSONObject;

public class WebappGenericBaseFragment extends Fragment implements WebappRunHost {
    public final UUID mClientUuid = UUID.randomUUID();
    protected int mCurrentlySelectedSubsceneId;
    protected boolean mExposingWebviewToViewSystemAsUi = true;
    protected View mLastCreatedView = null;
    protected String mLastUrlStringLoaded = null;
    public Map<String, UUID> mLinkedClientUuidMap = newLinkedClientMap();
    protected int mMainSubsceneId;
    private WebappSupport mPrivateWebAppSupportObject = null;
    protected QueuedLoadUrlContainer mQueuedLoadUrl = null;
    protected Lock queuedUrlResourceLock = new ReentrantLock();

    protected static Map<String, UUID> newLinkedClientMap() {
        return new HashMap();
    }

    public void setCreatedByLinkedClientEntry(String createdByClientIdAsString) {
        try {
            setCreatedByLinkedClientEntry(UUID.fromString(createdByClientIdAsString));
        } catch (Exception e) {
            Trace.debug("WebappGenericBaseFragment", "setCreatedByLinkedClientEntry", e);
        }
    }

    public void setCreatedByLinkedClientEntry(UUID createdByClientId) {
        if (createdByClientId == null) {
            Trace.debug("WebappGenericBaseFragment", "setCreatedByLinkedClientEntry: createdByClientId is null");
            return;
        }
        synchronized (this.mLinkedClientUuidMap) {
            this.mLinkedClientUuidMap.put("C", createdByClientId);
        }
    }

    public UUID queryLinkedClientEntry(String key) {
        if (key == null) {
            Trace.debug("WebappGenericBaseFragment", "queryLinkedClientEntry: key is null");
            return null;
        }
        UUID uuid;
        synchronized (this.mLinkedClientUuidMap) {
            uuid = (UUID) this.mLinkedClientUuidMap.get(key);
        }
        return uuid;
    }

    public UUID queryCreatedByLinkedClient() {
        return queryLinkedClientEntry("C");
    }

    public String lastUrlStringLoaded() {
        return this.mLastUrlStringLoaded;
    }

    public int clientUuidAsInt() {
        return clientUuidAsInt(clientUuid());
    }

    public static int clientUuidAsInt(UUID uuid) {
        if (uuid != null) {
            return uuid.hashCode();
        }
        Trace.debug("WebappGenericBaseFragment", "clientUuidAsInt: uuid is null");
        return 0;
    }

    public UUID clientUuid() {
        return this.mClientUuid;
    }

    public String clientUuidAsString() {
        return clientUuid().toString();
    }

    public QueuedLoadUrlContainer getQueuedLoadUrlWithAtomicClear() {
        this.queuedUrlResourceLock.lock();
        QueuedLoadUrlContainer rv = this.mQueuedLoadUrl;
        this.mQueuedLoadUrl = null;
        this.queuedUrlResourceLock.unlock();
        return rv;
    }

    public void newQueuedLoadUrl(String urlString, boolean useBootstrapScripts) {
        this.queuedUrlResourceLock.lock();
        this.mQueuedLoadUrl = useBootstrapScripts ? new QueuedLoadUrlContainer(urlString, LoadTypeE.WithBootstrapScripts) : new QueuedLoadUrlContainer(urlString, LoadTypeE.WithoutBootstrapScripts);
        this.queuedUrlResourceLock.unlock();
    }

    public long getWebappProcessId() {
        if (getPrivateWebAppSupportObject() != null) {
            return getPrivateWebAppSupportObject().getWebappProcessId();
        }
        return 0;
    }

    public void runDelayedConstruction() {
        if (this.mPrivateWebAppSupportObject == null) {
            this.mPrivateWebAppSupportObject = WebappSupport.makeMeMyWebappSupportObject(this);
            this.mPrivateWebAppSupportObject.getPrivateJsKitAccess().signalWebappRunHostOnCreate();
        }
    }

    public void onBootstrapScriptLoadedAndReady(String extraDataFromJsLoading) {
        if (extraDataFromJsLoading == null) {
            Trace.debug("WebappGenericBaseFragment", "onBootstrapScriptLoadedAndReady: extraDataFromJsLoading is null");
            return;
        }
        try {
            try {
                final String urlSpec = new JSONObject(URLDecoder.decode(extraDataFromJsLoading, "UTF-8")).optString("loadUrl");
                if (!urlSpec.isEmpty()) {
                    SyncStepRunnable rn = null;
                    if (urlSpec.endsWith("js")) {
                        rn = SyncStepRunnable.newRunnable(new Runnable() {
                            public void run() {
                                WebView webView = WebappGenericBaseFragment.this.getWebView();
                                if (webView != null) {
                                    webView.loadUrl("javascript:loadScript(\"" + urlSpec + "\")");
                                }
                            }
                        });
                    } else if (urlSpec.endsWith("html")) {
                        rn = SyncStepRunnable.newRunnable(new Runnable() {
                            public void run() {
                                WebView webView = WebappGenericBaseFragment.this.getWebView();
                                if (webView != null) {
                                    webView.loadUrl("javascript:loadBody(\"" + urlSpec + "\")");
                                }
                            }
                        });
                    }
                    if (rn != null) {
                        getActivity().runOnUiThread(rn);
                        rn.waitForRunToFinish(true);
                        try {
                            ((WebViewControlled) getWebView()).gatedInvalidateRunOnUiThread();
                        } catch (Exception e) {
                            Trace.debug("WebappGenericBaseFragment", "onBootstrapScriptLoadedAndReady", e);
                        }
                    }
                }
            } catch (Exception e2) {
                Trace.debug("WebappGenericBaseFragment", "onBootstrapScriptLoadedAndReady", e2);
            }
        } catch (Exception e22) {
            Trace.debug("WebappGenericBaseFragment", "onBootstrapScriptLoadedAndReady", e22);
        }
    }

    public void loadUrl(String urlString) {
        String paramString = null;
        this.mLastUrlStringLoaded = urlString;
        try {
            JSONObject jo = new JSONObject();
            jo.put("loadUrl", urlString);
            paramString = jo.toString();
        } catch (Exception e) {
            Trace.debug("WebappGenericBaseFragment", "onBootstrapScriptLoadedAndReady", e);
        }
        if (paramString != null) {
            try {
                paramString = "params=" + URLEncoder.encode(paramString, "UTF-8");
            } catch (UnsupportedEncodingException e2) {
                paramString = null;
            }
        }
        if (paramString != null) {
            WebView webView = getWebView();
            if (webView != null) {
                webView.loadUrl("file:///android_asset/jskit_startup.html?" + paramString);
                return;
            }
            PebbleWebappBaseActivity.LogSimpleDebug("queueing loadUrl url = %s", urlString);
            newQueuedLoadUrl(urlString, true);
        }
    }

    public void loadUrlNoBootstrapScripts(String urlString) {
        if (urlString != null) {
            this.mLastUrlStringLoaded = urlString;
            WebView webView = getWebView();
            if (webView != null) {
                webView.loadUrl(urlString);
                return;
            }
            PebbleWebappBaseActivity.LogSimpleDebug("queueing loadUrl url = %s", urlString);
            newQueuedLoadUrl(urlString, false);
        }
    }

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        runDelayedConstruction();
    }

    public Context getBackingContext() {
        return getActivity();
    }

    public WebappSupport getPrivateWebAppSupportObject() {
        return this.mPrivateWebAppSupportObject;
    }

    public void flagForSubsequentTeardownOnDestroy() {
        if (this.mPrivateWebAppSupportObject != null) {
            this.mPrivateWebAppSupportObject.flagForSubsequentTeardownOnDestroy();
        }
    }

    public JsKitAccessor getPrivateJsKitAccess() {
        return this.mPrivateWebAppSupportObject.getPrivateJsKitAccess();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        try {
            WebappSupport webappSupport = getPrivateWebAppSupportObject();
            if (webappSupport == null) {
                this.mExposingWebviewToViewSystemAsUi = false;
                this.mLastCreatedView = null;
                return super.onCreateView(inflater, container, savedInstanceState);
            }
            view = webappSupport.onCreateViewOnOwner(inflater, container, savedInstanceState);
            if (view == null) {
                PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onCreateView [fallback return]");
                this.mExposingWebviewToViewSystemAsUi = false;
                view = super.onCreateView(inflater, container, savedInstanceState);
            } else {
                PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onCreateView");
                this.mExposingWebviewToViewSystemAsUi = true;
            }
            this.mLastCreatedView = view;
            return view;
        } catch (Exception catchall) {
            Trace.debug("WebappGenericBaseFragment", "onCreateView", catchall);
        }
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        WebView webView = getWebView();
        QueuedLoadUrlContainer queuedLoadUrl = getQueuedLoadUrlWithAtomicClear();
        if (queuedLoadUrl == null) {
            Trace.debug("WebappGenericBaseFragment", "onActivityCreated: queuedLoadUrl is null");
        } else if (queuedLoadUrl.LoadType != LoadTypeE._INVALID_) {
            PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onCreate loadUrl-> %s", queuedLoadUrl);
            if (queuedLoadUrl.LoadType == LoadTypeE.WithBootstrapScripts) {
                loadUrl(queuedLoadUrl.UrlString);
            } else {
                loadUrlNoBootstrapScripts(queuedLoadUrl.UrlString);
            }
        }
    }

    public void onDestroyView() {
        if (getPrivateWebAppSupportObject() != null) {
            getPrivateWebAppSupportObject().onDestroyViewOnOwner();
        }
        super.onDestroyView();
        PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onDestroyView");
    }

    public void onCreate(Bundle savedInstanceState) {
        this.mMainSubsceneId = this.mClientUuid.hashCode();
        this.mCurrentlySelectedSubsceneId = this.mClientUuid.hashCode();
        super.onCreate(savedInstanceState);
        signalWebappRunHostOnCreate();
        if (getPrivateWebAppSupportObject() != null) {
            getPrivateWebAppSupportObject().onCreateOnOwner(savedInstanceState);
        }
        String str = " ------------------ --------- onCreate (si = %s)";
        Object[] objArr = new Object[1];
        objArr[0] = savedInstanceState == null ? "null)" : "not null)";
        PebbleWebappBaseActivity.LogSimpleDebug(str, objArr);
    }

    public void onDestroy() {
        boolean isFullTeardown = false;
        if (getPrivateWebAppSupportObject() != null) {
            isFullTeardown = getPrivateWebAppSupportObject().onDestroyOnOwner();
        }
        signalWebappRunHostOnDestroy(isFullTeardown);
        super.onDestroy();
        PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onDestroy");
    }

    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onSaveInstanceState");
    }

    public void onPause() {
        signalWebappRunHostOnPause();
        if (getPrivateWebAppSupportObject() != null) {
            getPrivateWebAppSupportObject().onPauseOnOwner();
        }
        super.onPause();
        PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onPause");
    }

    public void onStop() {
        signalWebappRunHostOnStop();
        super.onStop();
        PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onStop");
    }

    public void onResume() {
        super.onResume();
        WebappSupport webappSupport = getPrivateWebAppSupportObject();
        signalWebappRunHostOnResume();
        if (webappSupport != null) {
            webappSupport.onResumeOnOwner();
        }
        PebbleWebappBaseActivity.LogSimpleDebug(" ------------------ --------- onResume");
    }

    public WebView getWebView() {
        WebappSupport webappSupport = getPrivateWebAppSupportObject();
        if (webappSupport == null) {
            return null;
        }
        return webappSupport.getWebView();
    }

    public void onStart() {
        super.onStart();
        signalWebappRunHostOnStart();
    }

    public void signalWebappRunHostOnCreate() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnCreate();
        }
    }

    public void signalWebappRunHostOnDestroy(boolean isOnDestroyTheFullTeardown) {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnDestroy(isOnDestroyTheFullTeardown);
        }
    }

    public void signalWebappRunHostOnPause() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnPause();
        }
    }

    public void signalWebappRunHostOnResume() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnResume();
        }
    }

    public void signalWebappRunHostOnStop() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnStop();
        }
    }

    public void signalWebappRunHostOnStart() {
        JsKitAccessor jskit = getPrivateJsKitAccess();
        if (jskit != null) {
            jskit.signalWebappRunHostOnStart();
        }
    }
}
